package com.yqg.protection.controller;


import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yqg.protection.common.Result;
import com.yqg.protection.common.interceptor.SysLog;
import com.yqg.protection.controller.dto.MouthDataDto;
import com.yqg.protection.entity.EquipmentInputStore;
import com.yqg.protection.entity.EquipmentUnit;
import com.yqg.protection.entity.WarnRecord;
import com.yqg.protection.listenern.NoticeWebsocket;
import com.yqg.protection.mapper.UserMapper;
import com.yqg.protection.mapper.WarnRecordMapper;
import com.yqg.protection.service.IEquipmentInputStoreService;
import com.yqg.protection.service.IEquipmentUnitService;
import com.yqg.protection.service.IOrganizationService;
import com.yqg.protection.service.IWarnRecordService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * WarnRecordController 前端控制器
 *
 * @author zxf
 * @since 2024-01-01
 */
@RestController
@RequestMapping("/warn-record")
public class WarnRecordController {

    @Resource
    private IWarnRecordService warnRecordService;

    @Autowired
    private WarnRecordMapper warnRecordMapper;

    @Autowired
    IOrganizationService organizationService;

    @Autowired
    IEquipmentInputStoreService equipmentInputStoreService;

    @Autowired
    UserMapper userMapper;

    @Autowired
    IEquipmentUnitService equipmentUnitService;

    @Autowired
    private NoticeWebsocket noticeWebsocket;

    /**
     * 新增或者更新
     */
    @PostMapping("/edit")
    @SysLog("新增或者修改报警数据")
    public Result save(@RequestBody WarnRecord warnRecord) {
        if (ObjectUtil.isEmpty(warnRecord.getId())) {
            warnRecord.setCreateTime(LocalDateTime.now());
        }
        warnRecord.setIsDelete(0);
        return Result.success(warnRecordService.saveOrUpdate(warnRecord));
    }

    /**
     * 处理
     */
    @PostMapping("/deal")
    @SysLog("处理报警")
    public Result deal(@RequestBody WarnRecord warnRecord) {
        boolean flag;
        if (warnRecord.getTeleNotification().equals("1") && warnRecord.getFaultReport().equals("1") && warnRecord.getEliminHidDang().equals("1") && warnRecord.getFieldSurvey().equals("1")) {
            warnRecord.setIsDeal(1);
            warnRecord.setProcessingTime(LocalDateTime.now());
            flag = warnRecordService.saveOrUpdate(warnRecord);
            LambdaQueryWrapper<WarnRecord> warnRecordQueryWrapper = new LambdaQueryWrapper<>();
            warnRecordQueryWrapper.eq(WarnRecord::getIsDelete, 0);
            warnRecordQueryWrapper.eq(WarnRecord::getIsDeal, 0);
            if (warnRecord.getPartModel() != null && !warnRecord.getPartModel().equals("")) {
                warnRecordQueryWrapper.eq(WarnRecord::getPartModel, warnRecord.getPartModel());
            }
            warnRecordQueryWrapper.eq(WarnRecord::getEquipmentInputStoreId, warnRecord.getEquipmentInputStoreId());
            List<WarnRecord> warnRecords = warnRecordService.list(warnRecordQueryWrapper);
            if (warnRecords.size() == 0) {
                if (warnRecord.getPartModel() != null && !warnRecord.getPartModel().equals("")) {
                    LambdaQueryWrapper<EquipmentUnit> equipmentUnitQueryWrapper = new LambdaQueryWrapper<>();
                    equipmentUnitQueryWrapper.eq(EquipmentUnit::getPartModel, warnRecord.getPartModel());
                    equipmentUnitQueryWrapper.eq(EquipmentUnit::getEquipmentInputStoreId, warnRecord.getEquipmentInputStoreId());
                    equipmentUnitQueryWrapper.eq(EquipmentUnit::getIsDelete, 0);
                    EquipmentUnit equipmentUnit = equipmentUnitService.getOne(equipmentUnitQueryWrapper);
                    equipmentUnit.setWarnStateNum("0");
                    equipmentUnitService.saveOrUpdate(equipmentUnit);
                }
                EquipmentInputStore equipmentInputStore = equipmentInputStoreService.getById(warnRecord.getEquipmentInputStoreId());
                equipmentInputStore.setState("0");
                equipmentInputStoreService.saveOrUpdate(equipmentInputStore);
            }
//            Set<Long> sendUserIds = noticeWebsocket.conns.keySet();
//            if (sendUserIds.size() > 0) {
//                EquipmentInputStore equipmentInputStore = equipmentInputStoreService.getById(warnRecord.getEquipmentInputStoreId());
//                Organization organization = organizationService.getById(equipmentInputStore.getOrganization());
//                List<Long> userIds = userMapper.getAllUsersByOrganId(organization.getLevel(), organization.getCountry(),
//                        organization.getScTeam(), organization.getFcTeam(),
//                        organization.getFbTeam(), organization.getCommunity(),
//                        organization.getBuilding(), organization.getUnit(),
//                        organization.getFloor(), organization.getRoom(),
//                        sendUserIds, equipmentInputStore.getClientId());
//
//                HashMap<String, Object> noticeInfo = new HashMap<>();
//                noticeInfo.put("type", "endAlarm");
//                noticeInfo.put("msg", warnRecord.getWarnAddr() + (warnRecord.getWarnStateNum().equals("1")?"报警":"故障"));
//                for (Long userId:userIds) {
//                    System.out.println(userId+"-----------");
//                    noticeWebsocket.sendMessageByUserId(userId, noticeInfo);
//                }
//            }
        } else {
            flag = warnRecordService.saveOrUpdate(warnRecord);
        }
        return Result.success(flag);
    }

    /**
     * 删除
     */
    @DeleteMapping("delete/{id}")
    @SysLog("删除报警数据")
    public Result delete(@PathVariable Integer id) {
        WarnRecord warnRecord = warnRecordService.getById(id);
        warnRecord.setIsDelete(1);
        return Result.success(warnRecordService.saveOrUpdate(warnRecord));
    }

    /**
     * 查询所有
     */
    @GetMapping("/all")
    public Result findAll(Long organizationId,
                          Integer level,
                          String isAllClient,
                          @RequestParam List<Long> clientIds,
                          Long clientId) {
        List<WarnRecord> list = warnRecordMapper.selectlist(level, organizationId, isAllClient, clientIds, clientId);
        return Result.success(list);
    }

    @GetMapping("/todayAllPage")
    public Result findTodayAll(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               Long organizationId,
                               Integer level,
                               String isAllClient,
                               @RequestParam List<Long> clientIds) {
        pageNum = pageNum * pageSize - pageSize;
        String startTime = DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd 00:00:00");
        String endTime = DateFormatUtils.format(System.currentTimeMillis() + 24 * 60 * 60 * 1000, "yyyy-MM-dd 00:00:00");
        List<WarnRecord> list = warnRecordMapper.todayAllPage(pageNum, pageSize, level, organizationId, isAllClient, clientIds, startTime, endTime);
        Integer count = warnRecordMapper.findTodayWarnCount(organizationId, level, isAllClient, clientIds);
        HashMap<String, Object> map = new HashMap<>();
        map.put("record", list);
        map.put("total", count);
        return Result.success(map);
    }

    /**
     * 根据id查询
     */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(warnRecordService.getById(id));
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           String clientName,
                           String equipmentName,
                           String equipmentId,
                           Integer level,
                           Long organizationId,
                           String isMisinformation,
                           String warnTypeNum,
                           String warnStateNum,
                           Integer isDeal,
                           String startTime,
                           String endTime,
                           String isAllClient,
                           @RequestParam List<Long> clientIds,
                           Long id) {
        pageNum = pageNum * pageSize - pageSize;
        List<WarnRecord> warnRecords = warnRecordMapper.findPage(pageNum, pageSize, clientName, equipmentName, equipmentId, level, organizationId, isMisinformation, warnTypeNum, warnStateNum, isDeal, startTime, endTime, isAllClient, clientIds, id);
        Long count = warnRecordMapper.findPageCount(clientName, equipmentName, equipmentId, level, organizationId, isMisinformation, warnTypeNum, warnStateNum, isDeal, startTime, endTime, isAllClient, clientIds);
        HashMap<String, Object> map = new HashMap<>();
        map.put("record", warnRecords);
        map.put("total", count);
        return Result.success(map);
    }

    @GetMapping("/findTodayAllCount")
    public Result findTodayAllCount(Long organizationId, Integer level,
                                    String isAllClient,
                                    @RequestParam List<Long> clientIds,
                                    Long clientId) {
        String startTime = DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd 00:00:00");
        String endTime = DateFormatUtils.format(System.currentTimeMillis() + 24 * 60 * 60 * 1000, "yyyy-MM-dd 00:00:00");
        List<WarnRecord> list = warnRecordMapper.selectTodaylist(level, organizationId, isAllClient, clientIds, startTime, endTime, clientId);
        Map<Integer, List<WarnRecord>> collect = list.stream().collect(Collectors.groupingBy(WarnRecord::getIsDeal));
        HashMap<Object, Object> map = new HashMap<>();
        map.put("total", list.size());
        if (collect.get(1) != null) {
            map.put("processed", collect.get(1).size());
        } else {
            map.put("processed", 0);
        }
        if (collect.get(0) != null) {
            map.put("unprocessed", collect.get(0).size());
        } else {
            map.put("unprocessed", 0);
        }
        return Result.success(map);
    }

    @GetMapping("/findMouthData")
    public Result findMouthData(String startTime,
                                String endTime,
                                Long clientId,
                                String isMisinformation,
                                Long organizationId,
                                Integer level,
                                String isAllClient,
                                @RequestParam List<Long> clientIds) {
        List<MouthDataDto> list = warnRecordMapper.findMouthData(level, organizationId, clientId, isMisinformation, startTime, endTime, isAllClient, clientIds);
        return Result.success(list);
    }

    @ApiOperation("导出数据")
    @GetMapping("/export")
    public void export(HttpServletResponse response,
                       String clientName,
                       String equipmentName,
                       String equipmentId,
                       Integer level,
                       Long organizationId,
                       String warnTypeNum,
                       String warnStateNum,
                       String isMisinformation,
                       Integer isDeal,
                       String startTime,
                       String endTime,
                       String isAllClient,
                       @RequestParam List<Long> clientIds) {
        warnRecordService.export(response, clientName, equipmentName, equipmentId, level, organizationId, isMisinformation, warnTypeNum, warnStateNum, isDeal, startTime, endTime, isAllClient, clientIds);
    }

    @ApiOperation("导入数据")
    @PostMapping("/importData")
    @SysLog("导入报警数据")
    public void importData(MultipartFile file) {
        warnRecordService.importData(file);
    }

    @GetMapping("/findTodayProcessScore")
    public Result findTodayProcessScore(Long organizationId, Integer level,
                                        String isAllClient,
                                        @RequestParam List<Long> clientIds) {
        String startTime = DateFormatUtils.format(System.currentTimeMillis(), "yyyy-MM-dd 00:00:00");
        String endTime = DateFormatUtils.format(System.currentTimeMillis() + 24 * 60 * 60 * 1000, "yyyy-MM-dd 00:00:00");
        List<WarnRecord> list = warnRecordMapper.selectTodaylist(level, organizationId, isAllClient, clientIds, startTime, endTime, null);
        Map<Integer, List<WarnRecord>> collect = list.stream().collect(Collectors.groupingBy(WarnRecord::getIsDeal));
        HashMap<Object, Object> map = new HashMap<>();
        map.put("total", list.size());
        if (collect.get(1) != null) {
            int size = collect.get(1).size();
            map.put("processed", size);
            map.put("score", NumberUtil.round((double) size / list.size() * 100, 0) + "%");
        } else {
            map.put("processed", 0);
            map.put("score", "0%");
        }
        return Result.success(map);
    }

    /**
     * 分页查询APP
     */
    @GetMapping("/pageApp")
    public Result findPageApp(@RequestParam Integer pageNum,
                              @RequestParam Integer pageSize,
                              Integer level,
                              Long organizationId,
                              Integer isDeal,
                              String isAllClient,
                              @RequestParam List<Long> clientIds,
                              Long equipmentInputStoreId) {
        pageNum = pageNum * pageSize - pageSize;
        List<WarnRecord> warnRecords = warnRecordMapper.findPageApp(pageNum, pageSize, level, organizationId, isDeal, isAllClient, clientIds, equipmentInputStoreId);
        Long count = warnRecordMapper.findPageAppCount(level, organizationId, isDeal, isAllClient, clientIds, equipmentInputStoreId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("record", warnRecords);
        map.put("total", count);
        return Result.success(map);
    }

    @GetMapping("/getCountByState")
    @ApiOperation("根据报警状态查询数量")
    public Result getCountByState(Integer level,
                                  Long organizationId,
                                  String isAllClient,
                                  @RequestParam List<Long> clientIds) {
        List<Map<String, Integer>> list = warnRecordMapper.getCountByState(level, organizationId, isAllClient, clientIds);
        return Result.success(list);
    }
}

